import Vue from 'vue';
import Vuex from 'vuex';

const { user } = require('./config');

Vue.use(Vuex);

/**
 * 是否使用本地数据
 */
const IS_LOCALHOST = process.env.NODE_ENV === 'development';
const IS_QA = process.env.NODE_ENV === 'qa';

/**
 * 延时方法
 * @param {Number} time
 * @returns
 */
const delay = function (time) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve();
        }, time * 1000);
    });
};

/**
 * 调用原生方法获取用户信息
 * @returns
 */
const getLoginInfo = function (mock) {
    return new Promise((resolve, reject) => {
        try {
            if (mock) {
                return resolve(user[mock] || user['default']);
            } else {
                app.link.getLoginInfo(function (result) {
                    resolve(result);
                });
            }
        } catch (e) {
            console.log('app.link.getLoginInfo is err:', e);
            if (IS_LOCALHOST) {
                return resolve(user['qyx']);
            }
            // await delay(1);
            // resolve(await getLoginInfo());
        }
    });
};

const store = new Vuex.Store({
    state: {
        mztUser: {},
    },
    mutations: {
        setMztUser: (state, data) => {
            state.mztUser = data;
        },
    },
    actions: {
        async getMztUser({ commit, state }, mock) {
            try {
                // 用户信息
                if (JSON.stringify(state.mztUser) === '{}') {
                    let data = await getLoginInfo(mock);
                    commit('setMztUser', data);
                }
            } catch (e) {
                console.log('getMztUser is err:', e);
            }
        },
    },
});
export default store;
